/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package posartenobsa;

import Facturacion.CrearFactura;
import SQL.Insertar;
import com.sun.data.provider.impl.CachedRowSetDataProvider;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.sql.rowset.CachedRowSetXImpl;
import com.sun.webui.jsf.component.Alert;
import com.sun.webui.jsf.component.Button;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.StaticText;
import com.sun.webui.jsf.component.TextField;
import java.sql.*;
import javax.faces.FacesException;
import javax.faces.component.html.HtmlInputText;
import javax.faces.convert.DoubleConverter;
import javax.faces.convert.IntegerConverter;
import javax.faces.event.ValueChangeEvent;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @version Vender.java
 * @version Created on 6/06/2012, 08:58:51 PM
 * @author Fabio
 */
public class VenderP extends AbstractPageBean {

    String SQL, Producto;
    String cc = "jdbc:postgresql://localhost:5432/WEBARTENOBSA?user=postgres&password=pokemon";
    Insertar in = new Insertar();
    CrearFactura CF = new CrearFactura();
    int Cantidad, resul;
    double Precio, Totalp, TotalVenta, IVA;
    String Factura = "\nProducto \t\tDescripción \t\tCantidad \tValor Unitario\t\tValor Total\r\n";
    String DComprador;
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
        productoDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.productoRowSet}"));
        usuarioDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.usuarioRowSet}"));
        socioDataProvider.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{SessionBean1.socioRowSet}"));
        productoDataProvider1.setCachedRowSet((javax.sql.rowset.CachedRowSet) getValue("#{VenderP.productoRowSet}"));
        productoRowSet.setDataSourceName("java:comp/env/jdbc/public_PostgreSQL");
        productoRowSet.setCommand("SELECT ALL \"public\".producto.idproducto, \"public\".producto.nombre_producto, \"public\".producto.tipo_producto, \"public\".producto.producto_activo, \"public\".producto.descripcion, \"public\".producto.cantidad  FROM \"public\".producto");
        productoRowSet.setTableName("producto");
    }
    private HtmlInputText TEXTProducto = new HtmlInputText();

    public HtmlInputText getTEXTProducto() {
        return TEXTProducto;
    }

    public void setTEXTProducto(HtmlInputText hit) {
        this.TEXTProducto = hit;
    }
    private Button BVender = new Button();

    public Button getBVender() {
        return BVender;
    }

    public void setBVender(Button b) {
        this.BVender = b;
    }
    private Alert alertaProductosinsuficientes = new Alert();

    public Alert getAlertaProductosinsuficientes() {
        return alertaProductosinsuficientes;
    }

    public void setAlertaProductosinsuficientes(Alert a) {
        this.alertaProductosinsuficientes = a;
    }
    private Alert alertaProductoVendido = new Alert();

    public Alert getAlertaProductoVendido() {
        return alertaProductoVendido;
    }

    public void setAlertaProductoVendido(Alert a) {
        this.alertaProductoVendido = a;
    }
    private CachedRowSetDataProvider productoDataProvider = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getProductoDataProvider() {
        return productoDataProvider;
    }

    public void setProductoDataProvider(CachedRowSetDataProvider crsdp) {
        this.productoDataProvider = crsdp;
    }
    private CachedRowSetDataProvider usuarioDataProvider = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getUsuarioDataProvider() {
        return usuarioDataProvider;
    }

    public void setUsuarioDataProvider(CachedRowSetDataProvider crsdp) {
        this.usuarioDataProvider = crsdp;
    }
    private CachedRowSetDataProvider socioDataProvider = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getSocioDataProvider() {
        return socioDataProvider;
    }

    public void setSocioDataProvider(CachedRowSetDataProvider crsdp) {
        this.socioDataProvider = crsdp;
    }
    private CachedRowSetDataProvider productoDataProvider1 = new CachedRowSetDataProvider();

    public CachedRowSetDataProvider getProductoDataProvider1() {
        return productoDataProvider1;
    }

    public void setProductoDataProvider1(CachedRowSetDataProvider crsdp) {
        this.productoDataProvider1 = crsdp;
    }
    private CachedRowSetXImpl productoRowSet = new CachedRowSetXImpl();

    public CachedRowSetXImpl getProductoRowSet() {
        return productoRowSet;
    }

    public void setProductoRowSet(CachedRowSetXImpl crsxi) {
        this.productoRowSet = crsxi;
    }
    private IntegerConverter product1Converter = new IntegerConverter();

    public IntegerConverter getProduct1Converter() {
        return product1Converter;
    }

    public void setProduct1Converter(IntegerConverter ic) {
        this.product1Converter = ic;
    }
    private IntegerConverter product2Converter = new IntegerConverter();

    public IntegerConverter getProduct2Converter() {
        return product2Converter;
    }

    public void setProduct2Converter(IntegerConverter ic) {
        this.product2Converter = ic;
    }
    private IntegerConverter product3Converter = new IntegerConverter();

    public IntegerConverter getProduct3Converter() {
        return product3Converter;
    }

    public void setProduct3Converter(IntegerConverter ic) {
        this.product3Converter = ic;
    }
    private StaticText DES1 = new StaticText();

    public StaticText getDES1() {
        return DES1;
    }

    public void setDES1(StaticText st) {
        this.DES1 = st;
    }
    private DropDown product1 = new DropDown();

    public DropDown getProduct1() {
        return product1;
    }

    public void setProduct1(DropDown dd) {
        this.product1 = dd;
    }
    private TextField CANT1 = new TextField();

    public TextField getCANT1() {
        return CANT1;
    }

    public void setCANT1(TextField tf) {
        this.CANT1 = tf;
    }
    private TextField VALU1 = new TextField();

    public TextField getVALU1() {
        return VALU1;
    }

    public void setVALU1(TextField tf) {
        this.VALU1 = tf;
    }
    private StaticText VALTO1 = new StaticText();

    public StaticText getVALTO1() {
        return VALTO1;
    }

    public void setVALTO1(StaticText st) {
        this.VALTO1 = st;
    }
    private DoubleConverter doubleConverter1 = new DoubleConverter();

    public DoubleConverter getDoubleConverter1() {
        return doubleConverter1;
    }

    public void setDoubleConverter1(DoubleConverter dc) {
        this.doubleConverter1 = dc;
    }
    private DropDown product2 = new DropDown();

    public DropDown getProduct2() {
        return product2;
    }

    public void setProduct2(DropDown dd) {
        this.product2 = dd;
    }
    private StaticText DES2 = new StaticText();

    public StaticText getDES2() {
        return DES2;
    }

    public void setDES2(StaticText st) {
        this.DES2 = st;
    }
    private TextField CANT2 = new TextField();

    public TextField getCANT2() {
        return CANT2;
    }

    public void setCANT2(TextField tf) {
        this.CANT2 = tf;
    }
    private TextField VALU2 = new TextField();

    public TextField getVALU2() {
        return VALU2;
    }

    public void setVALU2(TextField tf) {
        this.VALU2 = tf;
    }
    private StaticText VALTO2 = new StaticText();

    public StaticText getVALTO2() {
        return VALTO2;
    }

    public void setVALTO2(StaticText st) {
        this.VALTO2 = st;
    }
    private StaticText VALIVA = new StaticText();

    public StaticText getVALIVA() {
        return VALIVA;
    }

    public void setVALIVA(StaticText st) {
        this.VALIVA = st;
    }
    private StaticText VALTOTAL = new StaticText();

    public StaticText getVALTOTAL() {
        return VALTOTAL;
    }

    public void setVALTOTAL(StaticText st) {
        this.VALTOTAL = st;
    }
    private DropDown product3 = new DropDown();

    public DropDown getProduct3() {
        return product3;
    }

    public void setProduct3(DropDown dd) {
        this.product3 = dd;
    }
    private StaticText DES3 = new StaticText();

    public StaticText getDES3() {
        return DES3;
    }

    public void setDES3(StaticText st) {
        this.DES3 = st;
    }
    private TextField CANT3 = new TextField();

    public TextField getCANT3() {
        return CANT3;
    }

    public void setCANT3(TextField tf) {
        this.CANT3 = tf;
    }
    private TextField VALU3 = new TextField();

    public TextField getVALU3() {
        return VALU3;
    }

    public void setVALU3(TextField tf) {
        this.VALU3 = tf;
    }
    private StaticText VALTO3 = new StaticText();

    public StaticText getVALTO3() {
        return VALTO3;
    }

    public void setVALTO3(StaticText st) {
        this.VALTO3 = st;
    }
    private TextField TFComprador = new TextField();

    public TextField getTFComprador() {
        return TFComprador;
    }

    public void setTFComprador(TextField tf) {
        this.TFComprador = tf;
    }
    private TextField TFIdentiComprador = new TextField();

    public TextField getTFIdentiComprador() {
        return TFIdentiComprador;
    }

    public void setTFIdentiComprador(TextField tf) {
        this.TFIdentiComprador = tf;
    }
    private TextField TFTelefonoComprador = new TextField();

    public TextField getTFTelefonoComprador() {
        return TFTelefonoComprador;
    }

    public void setTFTelefonoComprador(TextField tf) {
        this.TFTelefonoComprador = tf;
    }
    private TextField TFDireccionComprador = new TextField();

    public TextField getTFDireccionComprador() {
        return TFDireccionComprador;
    }

    public void setTFDireccionComprador(TextField tf) {
        this.TFDireccionComprador = tf;
    }

    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public VenderP() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("Vender Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
        productoDataProvider.close();
        usuarioDataProvider.close();
        socioDataProvider.close();
        productoDataProvider1.close();
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public String HPL_AUsuario1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return "case2";
    }

    public String HPL_ASocio_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return "case1";
    }

    public String hyperlink2_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return "case3";
    }

    public String HPL_ADeposito_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return "case4";
    }

    public String HPL_AExposicion1_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return "case5";
    }

    public String HPL_Vender_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String tabCUsuario_action() {
        // TODO: Process the action. Return value is a navigation
        //labeltotal.setText(null);
        //TFProductovender.setValue(null);
        alertaProductosinsuficientes.setVisible(false);
        alertaProductoVendido.setVisible(false);
        // case name where null will return to the same page.
        return null;
    }

    public String b_Modificarusuario1_action() {

        return null;
    }

    public String tabMSocio_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public String tabDSocio_action() {
        // TODO: Process the action. Return value is a navigation
        // case name where null will return to the same page.
        return null;
    }

    public void TF_precioproducto1_processValueChange(ValueChangeEvent vce) {
    }

    public String boton_Aceptar_action() {
       return null;
    }

    public String BVENDER_action() {
        if (CANT1.getValue() != null) {
            try {
                Cantidad = Integer.valueOf(String.valueOf(CANT1.getText()));

                Producto = String.valueOf(product1.getValue());

                Precio = Double.valueOf(String.valueOf(VALU1.getText()));
                Connection conexion = DriverManager.getConnection(cc);
                Statement comando = conexion.createStatement();
                String sql = "SELECT cantidad, descripcion FROM producto WHERE idproducto = " + Producto + ";";
                ResultSet resultado = comando.executeQuery(sql);

                while (resultado.next()) {
                    int numero = resultado.getInt("cantidad");
                    String descrip = resultado.getString("descripcion");
                    DES1.setText(descrip);
                    System.out.println("Cantidad leida: " + numero);
                    System.out.println("El numero leido fue: " + Cantidad);
                    if (Cantidad <= numero) {
                        resul = (numero - Cantidad);
                        System.out.println("El resultado es... " + resul);
                        SQL = ("UPDATE producto SET cantidad =" + resul + " WHERE idproducto = " + Producto + "");
                        Totalp = (Cantidad * Precio);
                        VALTO1.setText(Totalp);
                        alertaProductoVendido.setVisible(true);
                        alertaProductosinsuficientes.setVisible(false);
                        TotalVenta = TotalVenta + Totalp;
                        Factura =(Factura+"\t"+Producto+"\t"+descrip+"\t"+Cantidad+"\t"+
                                "\t"+Precio+"\t\t"+Totalp+"\r\n");

                    } else {

                        System.out.println("No se puede vender");
                        alertaProductosinsuficientes.setVisible(true);
                        alertaProductoVendido.setVisible(false);
                    }


                }
                resultado.close();
                comando.close();
                conexion.close();
            } catch (Exception ev) {
                System.out.println(ev.getMessage());
            }

            productoDataProvider.refresh();
            usuarioDataProvider.refresh();
            socioDataProvider.refresh();
        } else {
            System.out.println("No se va a vender");
        }

        ////////////////////PARA EL PRODUCTO 2

        if (CANT2.getValue() != null) {
            try {

                Producto = String.valueOf(product2.getValue());
                Cantidad = Integer.valueOf(String.valueOf(CANT2.getText()));
                Precio = Double.valueOf(String.valueOf(VALU2.getText()));
                Connection conexion = DriverManager.getConnection(cc);
                Statement comando = conexion.createStatement();
                String sql = "SELECT cantidad, descripcion FROM producto WHERE idproducto = " + Producto + ";";
                ResultSet resultado = comando.executeQuery(sql);

                while (resultado.next()) {
                    int numero = resultado.getInt("cantidad");
                    String descrip = resultado.getString("descripcion");
                    DES2.setText(descrip);
                    System.out.println("Cantidad leida: " + numero);
                    System.out.println("El numero leido fue: " + Cantidad);
                    if (Cantidad <= numero) {
                        resul = (numero - Cantidad);
                        System.out.println("El resultado es... " + resul);
                        SQL = ("UPDATE producto SET cantidad =" + resul + " WHERE idproducto = " + Producto + "");
                        in.insertar(SQL);
                        Totalp = (Cantidad * Precio);
                        VALTO2.setText(Totalp);
                        alertaProductoVendido.setVisible(true);
                        alertaProductosinsuficientes.setVisible(false);
                        TotalVenta = TotalVenta + Totalp;
                        Factura =(Factura+"\t"+Producto+"\t"+descrip+"\t"+Cantidad+"\t"+
                                "\t"+Precio+"\t\t"+Totalp+"\r\n");

                    } else {

                        System.out.println("No se puede vender");
                        alertaProductosinsuficientes.setVisible(true);
                        alertaProductoVendido.setVisible(false);
                    }


                }
                resultado.close();
                comando.close();
                conexion.close();
            } catch (Exception ev) {
                System.out.println(ev.getMessage());
            }

            productoDataProvider.refresh();
            usuarioDataProvider.refresh();
            socioDataProvider.refresh();
        } else {
            System.out.println("No se va a vender");
        }

        ////////////////////PARA EL PRODUCTO 3

        if (CANT3.getValue() != null) {
            try {

                Producto = String.valueOf(product3.getValue());
                Cantidad = Integer.valueOf(String.valueOf(CANT3.getText()));
                Precio = Double.valueOf(String.valueOf(VALU3.getText()));
                Connection conexion = DriverManager.getConnection(cc);
                Statement comando = conexion.createStatement();
                String sql = "SELECT cantidad, descripcion FROM producto WHERE idproducto = " + Producto + ";";
                ResultSet resultado = comando.executeQuery(sql);

                while (resultado.next()) {
                    int numero = resultado.getInt("cantidad");
                    String descrip = resultado.getString("descripcion");
                    DES3.setText(descrip);
                    System.out.println("Cantidad leida: " + numero);
                    System.out.println("El numero leido fue: " + Cantidad);
                    if (Cantidad <= numero) {
                        resul = (numero - Cantidad);
                        System.out.println("El resultado es... " + resul);
                        SQL = ("UPDATE producto SET cantidad =" + resul + " WHERE idproducto = " + Producto + "");
                        in.insertar(SQL);
                        Totalp = (Cantidad * Precio);
                        VALTO3.setText(Totalp);
                        alertaProductoVendido.setVisible(true);
                        alertaProductosinsuficientes.setVisible(false);
                        TotalVenta = TotalVenta + Totalp;
                        Factura =(Factura+"\t"+Producto+"\t"+descrip+"\t\t"+Cantidad+"\t"+
                                "\t"+Precio+"\t\t"+Totalp+"\r\n");
                    } else {

                        System.out.println("No se puede vender");
                        alertaProductosinsuficientes.setVisible(true);
                        alertaProductoVendido.setVisible(false);
                    }


                }
                resultado.close();
                comando.close();
                conexion.close();
            } catch (Exception ev) {
                System.out.println(ev.getMessage());
            }

            productoDataProvider.refresh();
            usuarioDataProvider.refresh();
            socioDataProvider.refresh();
        } else {
            System.out.println("No se va a vender");
        }
///////////////////// CALCULOS EXTRA   ////////////////
       DComprador=("Nombre Comprador: "+TFComprador.getValue()+"\r\n"+
               "Identificador Comprador: "+TFIdentiComprador.getValue()+"\r\n"+
               "Telefono Comprador: "+TFTelefonoComprador.getValue()+"\r\n"+
               "Direccion Comprador: "+TFDireccionComprador.getValue()+"\r\n");


        VALTOTAL.setText(TotalVenta);
        VALIVA.setText(TotalVenta * 0.16);
        CF.CREARF(Factura,DComprador,String.valueOf(TFIdentiComprador.getValue()));
        return null;
    }

    public String tabReportes_action() {
        productoDataProvider.refresh();
        usuarioDataProvider.refresh();
        socioDataProvider.refresh();
        return null;
    }

    public void product1_processValueChange(ValueChangeEvent event) {
        Producto = String.valueOf(product1.getValue());
        System.out.println("cambio");
        try {

                Connection conexion = DriverManager.getConnection(cc);
                Statement comando = conexion.createStatement();
                String sql = "SELECT descripcion FROM producto WHERE idproducto = " + Producto + ";";
                ResultSet resultado = comando.executeQuery(sql);

                while (resultado.next()) {
                    String descrip = resultado.getString("descripcion");
                    DES1.setText(descrip);
               }
                resultado.close();
                comando.close();
                conexion.close();
            } catch (Exception ev) {
                System.out.println(ev.getMessage());
            }


    }

    public void product2_processValueChange(ValueChangeEvent event) {
        Producto = String.valueOf(product2.getValue());
        System.out.println("cambio");
        try {

                Connection conexion = DriverManager.getConnection(cc);
                Statement comando = conexion.createStatement();
                String sql = "SELECT descripcion FROM producto WHERE idproducto = " + Producto + ";";
                ResultSet resultado = comando.executeQuery(sql);

                while (resultado.next()) {
                    String descrip = resultado.getString("descripcion");
                    DES2.setText(descrip);
               }
                resultado.close();
                comando.close();
                conexion.close();
            } catch (Exception ev) {
                System.out.println(ev.getMessage());
            }

    }

    public void product3_processValueChange(ValueChangeEvent event) {
        Producto = String.valueOf(product3.getValue());
        System.out.println("cambio");
        try {

                Connection conexion = DriverManager.getConnection(cc);
                Statement comando = conexion.createStatement();
                String sql = "SELECT cantidad, descripcion FROM producto WHERE idproducto = " + Producto + ";";
                ResultSet resultado = comando.executeQuery(sql);

                while (resultado.next()) {
                    String descrip = resultado.getString("descripcion");
                    DES3.setText(descrip);
               }
                resultado.close();
                comando.close();
                conexion.close();
            } catch (Exception ev) {
                System.out.println(ev.getMessage());
            }

    }
}
